package com.dkd.day20250618;

import com.dkd.day20250614.ListNode;

public class SolutionsortInList {
    public static void main(String[] args) {

    }

    public ListNode sortInList (ListNode head) {
        // write code here，归并排序
        if (head == null || head.next == null) {
            return head;
        }

        //使用快慢指针找到中的
        ListNode slow = head;
        ListNode fast = head.next;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }

        //分割链表
        ListNode mid = slow.next;
        slow.next = null;

        //继续分并
        ListNode left = sortInList(head);
        ListNode right = sortInList(mid);

        return merge(left, right);

    }


    ListNode merge(ListNode l1, ListNode l2) {
        //创建节点
        ListNode dummy = new ListNode(0);
        ListNode curr = dummy;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                curr.next = l1;
                l1 = l1.next;

            }else{
                curr.next = l2;
                l2 = l2.next;
            }
        }
        //处理剩余节点
        curr.next = l1 == null ? l2 : l1;
        return dummy.next;
    }
}
